<?php

namespace app\model;

use think\Model;
use think\facade\Cache;
use think\facade\Db;

class ClubModel extends Model
{
    protected $table = 'club';

    // 自动维护 created_at 和 updated_at 字段
    protected $autoWriteTimestamp = true;

    protected $schema = [
        'id' => 'int',
        'name' => 'string',
        'description' => 'string',
        'leader_id' => 'int',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // 关联社团负责人
    public function leader()
    {
        return $this->belongsTo(UserModel::class, 'leader_id');
    }

    // 数据验证
    public static function validateData($data)
    {
        $validate = new \think\Validate([
            'name'        => 'require|unique:club|max:255',
            'description' => 'max:1000',
            'leader_id'   => 'require|integer',
        ]);

        return $validate->check($data);
    }

    // 设置创建/更新时间（如需自定义逻辑）
    protected static function init()
    {
        self::event('before_insert', function ($club) {
            $club->created_at = $club->updated_at = time();
        });
    }

    // 获取社团缓存
    public static function getByIdWithCache($id)
    {
        $cacheKey = 'club_' . $id;
        $club = Cache::get($cacheKey);
        if (!$club) {
            $club = self::find($id);
            Cache::set($cacheKey, $club, 3600);  // 缓存1小时
        }
        return $club;
    }
}
